/**
 * Copyright © 2011 Software in Life Inc. All rights reserved.
 */
package com.softwareinlife.restful.server.alarm.dao;

import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.stereotype.Repository;

import com.softwareinlife.restful.server.alarm.model.AlarmModel;
import com.softwareinlife.restful.server.data.PMF;

/**
 * <b>Java Data Object Component for Alarm</b>
 * 
 * <p>
 * Business Logic Component
 * </p>
 * 
 * @author Jang, Sun-Jin(jangsunjin@softwareinlife.com)
 */
@Repository
public class AlarmJDO {

	/**
	 * Logger
	 */
	protected static Logger logger = Logger.getLogger("dao");

	/**
	 * Create or Update Model
	 * 
	 * @param model
	 */
	public void saveOrUpdate(AlarmModel model) {
		// Get PM
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();
		try {
			pm.makePersistent(model);
		} finally {
			if (!pm.isClosed()) {
				pm.close();
			}
		}
	}

	/**
	 * Read Models
	 * 
	 * @param model
	 */
	public List<AlarmModel> read() {
		// Return Model
		List<AlarmModel> results = null;
		
		// Get PM
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();
		Query query = null;
		try {
			query = pm.newQuery(AlarmModel.class);
			query.setOrdering("createdDate desc");
			
			results = (List<AlarmModel>)query.execute();
		} finally {
			if (query != null){
				query.closeAll();
			}
		}
		
		return results;
	}
	
	/**
	 * Read Model
	 * 
	 * @param model
	 */
	public AlarmModel read(long id) {
		// Return Model
		AlarmModel model = null;
		
		// Get PM
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();

		try {
			model = pm.getObjectById(AlarmModel.class, id);
		} finally {
			if (!pm.isClosed()) {
				pm.close();
			}
		}
		
		return model;
	}

	/**
	 * Delete Model
	 * 
	 * @param model
	 */
	public void delete(AlarmModel model) {
		// Get PM
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();

		try {
			pm.deletePersistent(model);
		} finally {
			if (!pm.isClosed()) {
				pm.close();
			}
		}
	}

	/**
	 * Delete Model
	 * 
	 * @param id
	 */
	public void delete(long id) {
		// Get PM
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();

		try {
			AlarmModel model = pm.getObjectById(AlarmModel.class, id);
			pm.deletePersistent(model);
		} finally {
			if (!pm.isClosed()) {
				pm.close();
			}
		}
	}
}
